package com.youdoneed.community.common.utils;

import com.google.gson.Gson;
import com.youdoneed.base.common.OkHttpUtils;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 百度翻译接口
 *
 * @author lixs
 * @Date 2017.6.21
 */
public class BaiduTranslate {
    //app id
    private static final String APP_ID = "20170620000059532";
    //密钥
    private static final String SECURITY_KEY = "HNz7gCOy_xPdPvDXupFp";
    //翻译URL
    private static final String TRANS_URL = "https://fanyi-api.baidu.com/api/trans/vip/translate";
    //GSON是线程安全的 可以共享
    private static final Gson GSON = new Gson();

    /**
     * 百度翻译结果。
     */
    public static class BaiduTransResult {
        // 翻译结果 {"from":"zh","to":"en","trans_result":[{"src":"\u4f60\u597d","dst":"Hello"}]}

        public String from;
        public String to;
        public List<TransResult> trans_result;

        public static class TransResult {
            public String src;
            public String dst;
        }
    }

    /**
     * 百度翻译接口（调用接口）
     *
     * @param body 内容
     * @param from 源语言
     * @param to   目标语言
     * @author lixs
     * @Date 2017.6.21
     */
    public static String getResult(String body, String from, String to) {
        String salt = String.valueOf(System.currentTimeMillis());
        //处理换行符
        body=body.replace("\n", "\uffff");
        System.out.println(body);
        String src = APP_ID + body + salt + SECURITY_KEY;
        String sign;
        try {
            sign = DigestUtils.md5DigestAsHex(src.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
           
        //返回相关结果
        BaiduTransResult transResult = OkHttpUtils.formPost(TRANS_URL)
                .param("appid", APP_ID)
                .param("salt", salt)
                .param("sign", sign)
                .param("q", body)
                .param("from", from)
                .param("to", to)
                .callForObject(BaiduTransResult.class);

        if (transResult != null && transResult.trans_result != null &&
                transResult.trans_result.size() > 0 && transResult.trans_result.get(0) != null) {
        	String result = transResult.trans_result.get(0).dst;
        	result = result.replace("\uffff", "\n");
            return result;
        }
        return "";
    }

    /**
     * 百度翻译接口（调用接口）
     *
     * @param body 内容（自动识别语言）
     * @param to   目标语言
     * @author lixs
     * @Date 2017.6.21
     */
    public static String getResult(String body, String to) {
        return getResult(body, "auto", to);
    }

//    public static void main(String[] args){
//    	System.out.println(getResult("pig\npig\ntime is flying\nfly\napple", "en", "zh"));
//    	System.out.println(getResult("time\ntime is flying\napple", "en", "zh"));
//    }

}
